#include "stdafx.h"
#include "SystemHandler.h"

#include "Core\XMLConnection.h"
#include "Core\Packages.h"
#include "Core\Logger.h"

#include "Poco\Format.h"

#include <sstream>

namespace ExamSystem
{
namespace Server
{
    CSystemHandler::CSystemHandler(CServerSystem *serverSystem, const SharedPtr<CXMLConnection> &connection)
        : m_serverSystem(serverSystem)
        , m_xmlConnection(connection)
    {
    }

    CSystemHandler::~CSystemHandler(void)
    {

    }

    void CSystemHandler::startElement(CXMLConnection *connection, const XMLString& uri, const XMLString& localName, const XMLString& qname, const Attributes& attributes)
    {
        if (localName == CPackage::labelPackage)
            m_currentPackage = packageManager.CreatePackage(attributes.getValue(CPackage::namespaceURI, CPackage::attributeType));

        if (m_currentPackage)
            m_currentPackage->startElement(uri, localName, qname, attributes);
    }

    void CSystemHandler::endElement(CXMLConnection *connection, const XMLString& uri, const XMLString& localName, const XMLString& qname)
    {
        if (m_currentPackage)
            m_currentPackage->endElement(uri, localName, qname);

        if (localName == CPackage::labelPackage && m_currentPackage)    // end of package
        {
            // process the package
            ProcessPackage();

            // reset the package
            m_currentPackage = NULL;
        }
    }

    void CSystemHandler::characters(CXMLConnection *connection, const XMLChar ch[], int start, int length)
    {
        if (m_currentPackage)
            m_currentPackage->characters(ch, start, length);
    }

    void CSystemHandler::SendPackage(CPackage *package)
    {
        package->WriteToStream(m_xmlConnection->GetSocketOutputStream());
    }

    void CSystemHandler::ProcessPackage(void)
    {
        if (m_currentPackage)
            systemLogger.trace(Poco::format("[%u] %s", m_currentPackage->m_sourseID, m_currentPackage->ToText()));
    }

}
}